package com.zfxt.biz.autoconfig;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by xuxing on 2018/8/31.
 */
@Configuration
@ConditionalOnClass(HttpClient.class)//当httpClient存在的情况下加载当前类
@EnableConfigurationProperties(HttpClientProperties.class)//自动加载配置类
public class HttpClientAutoConfiguration {

    private final HttpClientProperties properties;

    public HttpClientAutoConfiguration(HttpClientProperties properties){
        this.properties=properties;
    }
    @Bean
    @ConditionalOnMissingBean(HttpClient.class)//当没有此类的时候加载
    public HttpClient httpClient(){                                         //连接超时时间
        RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(properties.getConnectTimeOut())
                .setSocketTimeout(properties.getSocketTimeOut()).build();//构建requestConfig
        HttpClient client= HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setUserAgent(properties.getAgent())
                .setMaxConnPerRoute(properties.getMaxConnPerRoute()).setMaxConnTotal(properties.getMacConnTotaol())
                .build();
        return client;
    }

}
